package com.jia.springcloud.controller;


import com.jia.springcloud.entities.CommonResult;
import com.jia.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author 1038940655
 * @create 2021/1/19 19:47
 */
@RestController
public class OrderController {

    /**
     *   //    理解：消费者直接取用就好了，不需要service层，service层在另一台服务器上面（模拟拆分成两个服务器）
     * //    RestTemplate 供我们直接调用就可以了，注册到spring中
     *     //提供多种便捷访问远程http服务的方法，简单的RestFul服务模板
     */
    @Autowired
    private RestTemplate restTemplate;


    /**
     *  //    自定义一个常量
     * //    这里使用http来连接访问的
     *     //真实的情况是应该去注册中心去拿，现这样直接拿是层层递进的关系
     */
  //  private static final String REST_URL_PREFIX = "http://localhost:8001";

    private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-PAYMENT";

    @RequestMapping("/consumer/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Integer id){

        return restTemplate.getForObject(REST_URL_PREFIX+"/payment/get/"+id, CommonResult.class);



    }

    @RequestMapping("consumer/create")
    public CommonResult create(Payment payment){
        return restTemplate.postForObject(REST_URL_PREFIX+"/payment/create",payment,CommonResult.class);


    }


    @RequestMapping("/consumer/discovery")
    public Object discovery(){
        return restTemplate.getForObject(REST_URL_PREFIX+"/payment/discovery",Object.class);
    }

//    RestTemplate有两种返回结果，getForObject返回的json字符串，getForEntity返回的有响应头响应体等

    @RequestMapping("/consumer/getEntity/{id}")
    public CommonResult getPaymentByIdEntity(@PathVariable("id") Integer id){


        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(REST_URL_PREFIX + "/payment/get/" + id, CommonResult.class);

        if(entity.getStatusCode().is2xxSuccessful()){

            return entity.getBody();
        }

        return new CommonResult(444,"操作失败");
    }

    }
